import * as app from '../../common/utils/BaseApp'
import { deepClone, getDictName } from '@/utils'
import * as ck from '../../common/utils/validater'
import { hasActionPriv } from '@/utils/perm'
import * as elg from '../../common/utils/ElmGenerator'

import { getDictList, createDict, updateDict, deleteDict, deleteMulityDict } from '@/api/system/dict.data'
import { getDictTypeList, createDictType, updateDictType, deleteDictType } from '@/api/system/dict.type'
import langFile from './dict.lang'
const base = app.install({ langObj: langFile })
const pageMode = {
  add: 'add',
  detailAdd: 'detailAdd',
  update: 'update'
}
export default {
  mixins: [base],
  data() {
    return {
      formObj: {
        dictTypeList: [],
        treeDefaultProps: {
          children: 'children',
          label: 'dictTypeName'
        },
        searchForm: {
          // ----------------------- dictData 查询条件 ---------------------
          dictData: {
            dictType: '',
            dictId: '',
            dictName: ''
          },
          likeSearch: {
            dictData: ['dictId', 'dictName'],
            dictType: []
          }
        },
        addForm: {
          // ----------------------- dictData Form结构 ---------------------
          dictData: {
            id: undefined,
            dictType: '',
            dictId: '',
            dictName: '',
            memo: ''
          },
          // ----------------------- dictType Form结构 ---------------------
          dictType: {
            id: undefined,
            dictType: '',
            dictTypeName: '',
            memo: ''
          },
          showFlg: {
            dictData: false,
            dictType: false
          },
          showMode: {
            dictData: '',
            dictType: ''
          }
        }

      },
      listObj: {
        // ----------------------- dictData 列表 ---------------------
        dictData: {
          ...base.$gcom.getDefListObj(),
          selectedData: []
        },
        // ----------------------- dictType 列表 ---------------------
        dictType: {
          ...base.$gcom.getDefListObj(),
          selectedData: []
        }
      }
    }
  },
  computed: {
    isAddDictType() {
      const _target = this.formObj.addForm.showMode
      return _target.dictType === pageMode.add || _target.dictType === pageMode.detailAdd
    },
    isAddDictData() {
      const _target = this.formObj.addForm.showMode
      return _target.dictData === pageMode.add || _target.dictData === pageMode.detailAdd
    },
    isExistDictType() {
      return this.formObj.dictTypeList.filter((item) => {
        return item.dictType === this.formObj.addForm.dictData.dictType
      }).length > 0
    },
    // ----------------------- dictType 查询条件 ---------------------
    dictTypeSearchFormLayout() {
      const formItems = [
        hasActionPriv(['sys:dict_type:add']) === false ? null
          : elg.createButton(this, this.handleAddDictType, { langId: 'add', propsOpt: { icon: 'el-icon-edit' }}),
        hasActionPriv(['sys:dict_type:update']) === false ? null
          : elg.createButton(this, this.handleEditDictType, { langId: 'edit', propsOpt: { icon: 'el-icon-edit' }}),
        hasActionPriv(['sys:dict_type:delete']) === false ? null
          : elg.createButton(this, this.handleDeleteDictType, { langId: 'delete', propsOpt: { icon: 'el-icon-delete' }})
      ]
      const rules = { }
      return { formItems: formItems, rules: rules }
    },
    // ----------------------- dictType 列表 ---------------------
    dictTypeListLayout() {
      const hasDictDataList = [
        { id: '0', name: this.getLang('unexistDictData'), color: '#ed1941' },
        { id: '1', name: this.getLang('existDictData'), color: '#1890ff' }
      ]
      const itemColumns = [
        elg.createTableColumn(this, { bindId: 'dictType', align: 'center', width: 130 }),
        elg.createTableColumn(this, { bindId: 'dictTypeName', align: 'center', width: 130 }),
        elg.createTableColumn(this, { bindId: elg.createTag(this, { bindId: 'hasDictData', optionList: hasDictDataList }), align: 'center', width: 40 }),
        elg.createTableColumn(this, { bindId: 'memo', align: 'left' })
      ]
      const actionColumns = []
      return { columns: itemColumns, actions: actionColumns }
    },
    // ----------------------- dictType Form结构 ---------------------
    dictTypeSaveActionPriv() {
      return (this.isAddDictType && hasActionPriv(['sys:dict_type:add'])) ||
      (this.isAddDictType === false && hasActionPriv(['sys:dict_type:update']))
    },
    dictTypeAddFormLayout() {
      const formItems = [
        elg.createInput(this, { bindId: 'dictType', isDisabled: false }),
        elg.createInput(this, { bindId: 'dictTypeName' }),
        elg.createTextArea(this, { bindId: 'memo', isDisabled: false })
      ]
      const footerItems = [
        this.dictTypeSaveActionPriv === false ? null
          : elg.createButton(this, this.handleSaveDictType, { langId: 'confirm', actionValid: true, propsOpt: { icon: '' }})
      ]
      const rules = {
        dictType: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 50), ck.createUndlineEngNumWordValidater(this)
        ],
        dictTypeName: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 150)
        ],
        memo: [
          ck.createMaxLenValidater(this, 255)
        ]
      }
      return { formItems: formItems, footerItems: footerItems, rules: rules }
    },
    dictDataSearchFormLayout() {
      const formItems = [
        elg.createSelect(this, { bindId: 'dictType', optionList: elg.createChildOption(this.formObj.dictTypeList) }),
        elg.createInput(this, { bindId: 'dictId', propsOpt: { width: 180 }}),
        elg.createInput(this, { bindId: 'dictName', propsOpt: { width: 180 }}),
        hasActionPriv(['sys:dict_data:query']) === false ? null
          : elg.createButton(this, this.handleSearchDict, { langId: 'search', actionValid: true, propsOpt: { icon: 'el-icon-search' }}),
        elg.createBR(),
        hasActionPriv(['sys:dict_data:add']) === false ? null
          : elg.createButton(this, this.handleAddDictData, { langId: 'add', propsOpt: { icon: 'el-icon-edit' }}),
        hasActionPriv(['sys:dict_data:batch_delete']) === false ? null
          : elg.createButton(this, this.handleBatchDeleteDict, { langId: 'batchDelete', propsOpt: { icon: 'el-icon-delete' }})
      ]
      const rules = {
        dictType: [
          ck.createMaxLenValidater(this, 50)
        ],
        dictId: [
          ck.createMaxLenValidater(this, 30)
        ],
        dictName: [
          ck.createMaxLenValidater(this, 150)
        ]
      }
      return { formItems: formItems, rules: rules }
    },
    dictDataSaveActionPriv() {
      return (this.isAddDictData && hasActionPriv(['sys:dict_data:add'])) ||
      (this.isAddDictData === false && hasActionPriv(['sys:dict_data:update']))
    },
    dictDataAddFormLayout() {
      const formItems = [
        elg.createSelect(this, { bindId: 'dictType', isDisabled: !this.isAddDictData && this.isExistDictType,
          optionList: elg.createChildOption(this.formObj.dictTypeList) }),
        elg.createInput(this, { bindId: 'dictId' }),
        elg.createInput(this, { bindId: 'dictName' }),
        elg.createTextArea(this, { bindId: 'memo' })
      ]
      const footerItems = [
        this.dictDataSaveActionPriv === false ? null
          : elg.createButton(this, this.handleSaveDict, { langId: 'confirm', actionValid: true, propsOpt: { icon: '' }})
      ]
      const rules = {
        dictType: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 50), ck.createUndlineEngNumWordValidater(this)
        ],
        dictId: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 30), ck.createEngNumWordValidater(this)
        ],
        dictName: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 150)
        ],
        memo: [
          ck.createMaxLenValidater(this, 255)
        ]
      }
      return { formItems: formItems, footerItems: footerItems, rules: rules }
    },
    dictListLayout() {
      const itemColumns = [
        elg.createTableColumn(this, { bindId: 'dictType',
          formatter: {
            formatFnc: (row, v) => {
              return getDictName(this.formObj.dictTypeList, v)
            }
          }, align: 'center' }),
        elg.createTableColumn(this, { bindId: 'dictId', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'dictName', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'memo', align: 'center' })
      ]
      const actionColumns = [
        hasActionPriv(['sys:dict_data:update']) === false ? null
          : elg.createTableAction(this, { langId: 'edit', actionFnc: this.handleUpdateDictData }),
        hasActionPriv(['sys:dict_data:delete']) === false ? null
          : elg.createTableAction(this, { langId: 'delete', actionFnc: this.handleDeleteDict })
      ]
      return { columns: itemColumns, actions: actionColumns }
    }
  },
  created() {
    this.$gcom.formObj = deepClone(this.formObj)
    this.searchDictTypeList()
  },
  methods: {
    // ----------------------- dictType 新增 ---------------------
    handleAddDictType() {
      this.openDialog('dictType', pageMode.add)
    },
    // ----------------------- dictType 修正 ---------------------
    handleEditDictType() {
      if (this.listObj.dictType.selectedData.length === 0) {
        this.$showErrorMsg(this.getLang('message.rule.updataDictTypeNotSel'))
      } else {
        this.openDialog('dictType', pageMode.update, this.listObj.dictType.selectedData[0])
      }
    },
    searchDictListByDictType(dictType) {
      this.listObj.dictData.pagingDefine.page = 1
      this.searchDictList({ dictType: dictType })
    },
    handleDictTypeSelChange(selectedVal) {
      if (selectedVal.length > 0) {
        this.searchDictListByDictType(selectedVal[0].dictType)
      }
    },
    handleSearchDict() {
      this.validateAll(['searchForm'], () => {
        this.listObj.dictData.pagingDefine.page = 1
        this.searchDictList()
      })
    },
    handleAddDictData(row, index) {
      this.openDialog('dictData', pageMode.add)
    },
    handleUpdateDictData(row, index) {
      this.openDialog('dictData', pageMode.update, row)
    },
    handleSaveDictType() {
      this.validateAll(['dictTypeEditDlg'], async() => {
        if (this.isAddDictType) {
          await createDictType(this.formObj.addForm.dictType)
        } else {
          await updateDictType(this.formObj.addForm.dictType)
        }
        this.formObj.addForm.showFlg.dictType = false
        setTimeout(async() => {
          this.searchDictTypeList(true, this.formObj.addForm.dictType.dictType)
        }, 500)
      })
    },
    async handleDeleteDictType() {
      if (this.listObj.dictType.selectedData.length === 0) {
        this.$showErrorMsg(this.getLang('message.rule.deleteDictTypeNotSel'))
      } else {
        this.$showConfirm({ msg: this.getLang('message.rule.deleteDictTypeIncludeDict'), ok: async() => {
          await deleteDictType(this.listObj.dictType.selectedData[0].id)
          setTimeout(async() => {
            await this.searchDictTypeList()
          }, 500)
        } })
      }
    },
    handleSaveDict() {
      this.validateAll(['dictEditDlg'], async() => {
        if (this.isAddDictData) {
          await createDict(this.formObj.addForm.dictData)
          await this.searchDictTypeList(true, this.formObj.addForm.dictData.dictType)
        } else {
          await updateDict(this.formObj.addForm.dictData)
          this.searchDictList()
        }
        this.formObj.addForm.showFlg.dictData = false
        setTimeout(() => {
          this.listObj.dictData.isUpdate = !this.listObj.dictData.isUpdate
          this.$nextTick(() => {
            this.$refs['dictList'].flexTable.doLayout()
            this.$refs['dictList'].flexTable.$forceUpdate()
          })
        }, 0)
      })
    },
    async handleDeleteDict(row, index) {
      this.$showConfirm({ msg: this.getLang('message.rule.deleteDictData'), ok: async() => {
        await deleteDict(row.id)
        await this.searchDictTypeList(true, row.dictType)
      } })
    },
    async handleBatchDeleteDict() {
      if (this.listObj.dictData.selectedData.length === 0) {
        this.$showErrorMsg(this.getLang('message.rule.dictDataNotSel'))
      } else {
        this.$showConfirm({ msg: this.getLang('message.rule.deleteDictMulity'), ok: async() => {
          const ids = this.listObj.dictData.selectedData.map((item) => {
            return item.id
          })
          const dictType = this.listObj.dictData.selectedData[0].dictType
          await deleteMulityDict(ids)
          setTimeout(async() => {
            await this.searchDictTypeList(true, dictType)
          }, 500)
        } })
      }
    },
    // ----------------------- dict列表查询 ---------------------
    async searchPagingDict() {
      await this.searchDictList(null)
    },
    async searchDictList(searchForm = null) {
      const _target = this.listObj.dictData
      _target.listLineLoading = true

      const result = await getDictList({
        searchForm: searchForm === null ? this.formObj.searchForm.dictData : searchForm,
        likeSearch: this.formObj.searchForm.likeSearch.dictData,
        pagingDefine: this.listObj.dictData.pagingDefine
      })

      _target.selectedData = []
      _target.listLine = result.data.listLine
      _target.lineNum = result.data.lineNum

      setTimeout(() => {
        _target.listLineLoading = false
      }, 0)
    },
    // ----------------------- dictType列表查询 ---------------------
    async searchDictTypeList(relatedSearch = false, relatedDictType = null) {
      const _target = this.listObj.dictType
      _target.listLineLoading = true
      const result = await getDictTypeList()
      const resutLine = result.data.listLine.map((item) => {
        item.hasDictData = item.SysDictData.length > 0 ? '1' : '0'
        delete item.SysDictData
        return item
      })

      // 设置选中行
      this.listObj.dictType.selectedData = []
      if (relatedSearch) {
        resutLine.filter((item) => {
          // dictType 相同
          return item.dictType === relatedDictType
        }).forEach(async(row) => {
          this.listObj.dictType.selectedData = [row]
          this.searchDictListByDictType(row.dictType)
        })
      } else {
        // 默认选择第一条
        if (resutLine.length > 0) {
          this.listObj.dictType.selectedData = [resutLine[0]]
          this.searchDictListByDictType(resutLine[0].dictType)
        }
      }

      _target.listLine = resutLine
      _target.lineNum = result.data.lineNum
      this.formObj.dictTypeList = result.data.listLine.map((item) => {
        return { id: item.dictType, name: item.dictTypeName }
      })

      setTimeout(() => {
        _target.listLineLoading = false
      }, 0)
    },

    // ----------------------- Open Dialog ---------------------
    openDialog(target, mode, row, index) {
      const data = row === undefined ? this.$gcom.formObj.addForm[target] : row
      this.formObj.addForm[target] = { ...data }
      this.formObj.addForm.showFlg[target] = true
      this.formObj.addForm.showMode[target] = mode
    }
  }
}
